package com.east.service.task.impl;

import com.east.bean.Task;
import com.east.bean.TaskImage;
import com.east.bean.User;
import com.east.dao.TaskImageMapper;
import com.east.dao.TaskMapper;
import com.east.service.task.TaskService;
import com.east.utils.BaseUtil;
import com.east.utils.Pagenation;
import com.east.utils.StringUtils;
import com.fasterxml.jackson.databind.deser.Deserializers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
@Service
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskMapper taskMapper;
    @Autowired
    private TaskImageMapper taskImageMapper;
    @Value("${file.dir}")
    private String fileUploadFolder;
    @Override
    public Page<Task> selectAll(Pagenation pagenation,User user) {
        Page<Task> startPage = PageHelper.startPage(pagenation.getPageNum(), pagenation.getPageSize(),"t_create_time desc");
        Example example = new Example(Task.class);
		   Criteria cr = example.createCriteria();
		   cr.andEqualTo("tDepId", user.getStaff().getDepartmentId());
        List<Task> tasks = taskMapper.selectByExample(example);
        if (tasks.size()>0){
            for (Task taskdetail:
                    tasks) {
                List<TaskImage> taskImages = taskImageMapper.selectByTask(taskdetail.gettId());
                taskdetail.setTaskImageList(taskImages);
            }
        }
        return startPage;
    }
    @Transactional
    @Override
    public int insert(Task task) {
        int insert = taskMapper.insert(task);
        if (insert>0){
            if (task.getTaskImageList()!=null){
                for (TaskImage taskImage:
                        task.getTaskImageList()) {
                    taskImage.setTiTaskId(task.gettId());
                }
                taskImageMapper.insertList(task.getTaskImageList());
            }
        }
        return insert;
    }
    @Transactional
    @Override
    public int insertByOwn(Task task,User token) {
        task.settWorkload(0);
        task.settCreateTime(new Date());
        task.settCreatePeopleId(BaseUtil.Token().getuId());
        task.settDesigneeId(token.getStaff().getsId());
        task.settDepId(token.getStaff().getDepartmentId());
        task.settDepName(token.getStaff().getDepartmentName());
        task.settDesigneeName(token.getStaff().getsName());
        task.settCreatePeopleName(BaseUtil.Token().getuAccount());
        int insert = taskMapper.insert(task);
        if (task.getTaskImageList()!=null){
            for (TaskImage taskImage:
                    task.getTaskImageList()) {
                taskImage.setTiTaskId(task.gettId());
            }
            taskImageMapper.insertList(task.getTaskImageList());
        }
        return insert;
    }
    @Transactional
    @Override
    public int delete(Integer[] ids) {
        int i = taskMapper.deleteByids(ids);
        for (Integer id:
             ids) {
            taskImageMapper.deleteByTask(id);
//            删除本地资源
            Example example = new Example(TaskImage.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("tiTaskId",id);
            List<TaskImage> taskImages = taskImageMapper.selectByExample(example);
            for (TaskImage taskImage:
                    taskImages) {
                if (StringUtils.isNotBlank(taskImage.getTiUrl())){
                    deletepho(taskImage.getTiUrl());
                }
            }
        }
        return i;
    }
    @Transactional
    @Override
    public int update(Task task) {
        return taskMapper.updateByPrimaryKey(task);
    }

    @Override
    public Page<Task> selectBy(Pagenation pagenation, Task task) {
        Page<Task> startPage = PageHelper.startPage(pagenation.getPageNum(), pagenation.getPageSize(),"t_create_time desc");
        List<Task> tasks = taskMapper.selectBy(task);
        if (tasks.size()>0){
            for (Task taskdetail:
                    tasks) {
                List<TaskImage> taskImages = taskImageMapper.selectByTask(taskdetail.gettId());
                taskdetail.setTaskImageList(taskImages);
            }
        }
        return startPage;
    }

    @Override
    public int updateByState(Task task) {
        task.settState(1);
        return taskMapper.updateByPrimaryKeySelective(task);
    }

    @Override
    public int countByStatus(Task task) {
            Example example = new Example(task.getClass());
            Example.Criteria criteria = example.createCriteria();
            if (task.gettState()!=null){
                criteria.andEqualTo("tState",task.gettState());
            }
            if (BaseUtil.Token().getuId()!=null){
                criteria.andEqualTo("tCreatePeopleId",BaseUtil.Token().getuId());
            }
            return taskMapper.selectCountByExample(example);
    }

    @Override
    public List<Task> selectPro() {
        return taskMapper.selectPro();
    }

    @Override
    public List<Task> selectSumWork() {
        return taskMapper.selectSumWork();
    }

    @Override
    public List<TaskImage> uploadTaskImage(MultipartFile[] files, Integer tId) {
        if(files.length==0) {
            return null;
        }
        //将文件以 文件目录/年/月日/文件名的情况来存储
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH)+1;
        int day = cal.get(Calendar.DATE);
        String monthString;
        String dayString;
        if(month < 10) {
            monthString = "0" + month;
        } else {
            monthString = String.valueOf(month);
        }
        if(day < 10) {
            dayString = "0" + day;
        } else {
            dayString = String.valueOf(day);
        }
        StringBuilder sbd = new StringBuilder();
        sbd.append(year).append("/")
                .append(monthString).append(dayString).append("/");

        //上传文件目录不存在时创建该目录
        File dir = new File(fileUploadFolder + sbd.toString());
        if(!dir.exists()) {
            dir.mkdirs();
        }
        // 获得当前时间
        DateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        // 转换为字符串
        String formatDate = format.format(new Date());
        List<TaskImage> list =new ArrayList<TaskImage>();
        TaskImage record=null;
        for(int i=0;i<files.length;i++){
            //获取文件名
            String filename = files[i].getOriginalFilename();
            //文件名后缀
            String pexfix=filename.substring(filename.lastIndexOf("."));
            byte[] bytes = new byte[0];
            Path path = Paths.get(fileUploadFolder + sbd.toString()+formatDate+String.valueOf(i)+pexfix);
            try {
                bytes = files[i].getBytes();
                //文件写入磁盘
                Files.write(path, bytes);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            record=new TaskImage();
            record.setTiUrl(sbd.toString()+formatDate+String.valueOf(i)+pexfix);
            record.setTiName(filename);
            //新增时tId为空，修改时需传对应tId
            if (tId!=null){
                record.setTiTaskId(tId);
            }
            list.add(record);
        }
        if (tId!=null && ! list.isEmpty()) {
            taskImageMapper.insertList(list);
        }
        return list;
    }

    @Override
    public int deletepho(String url) {
        try {
            String filePath = fileUploadFolder+url;
            filePath = filePath.toString();
            java.io.File myDelFile = new java.io.File(filePath);
            myDelFile.delete();
            Example example = new Example(TaskImage.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("tiUrl",url);
            int i = taskImageMapper.deleteByExample(example);
            return i;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int sumWork() {
        return taskMapper.sumWork();
    }

    @Override
    public Task selectBytId(Task task) {
        if (task.gettId()!=null){
            Task task1 = taskMapper.selectByPrimaryKey(task.gettId());
            List<TaskImage> taskImages = taskImageMapper.selectByTask(task1.gettId());
            task1.setTaskImageList(taskImages);
            return task1;
        }
        return null;
    }
}
